<template>
  <div class="view-fill">
    <div class="app-container-flex" v-if="!modifyInfo.visible && !showDetails">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btnList="fullInfo.btnList"
        :needReturn="!$route.query.processInstanceId"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="emit('returnBack')"
      >
        <template v-slot:full-button>
          <el-button
            v-if="
              $permission('pendCheckProduct:update') &&
              infoList.data.checkStatus === 1 &&
              !$route.query.processInstanceId
            "
            :plain="true"
            @click="update"
            >修改</el-button
          >
          <el-button
            v-if="
              $permission('pendCheckProduct:approve') &&
              infoList.data.checkStatus === 1 &&
              $store.state.permission.systemConfig
                .allow_slip_product_check_approval == 1
            "
            :plain="true"
            @click="approve"
            >批准</el-button
          >
          <el-button
            v-if="
              $permission('pendCheckProduct:reject') &&
              infoList.data.checkStatus === 1 &&
              $store.state.permission.systemConfig
                .allow_slip_product_check_approval == 1
            "
            :plain="true"
            @click="reject"
            >驳回</el-button
          >
          <el-button
            v-if="
              $permission('pendCheckProduct:refuse') &&
              infoList.data.checkStatus === 1 &&
              $store.state.permission.systemConfig
                .allow_slip_product_check_approval == 1
            "
            :plain="true"
            @click="refuse"
            >拒绝</el-button
          >
        </template>

        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList">
              <template v-slot:basic-filePathList>
                <div v-if="infoList.data.filePathList">
                  <eleGallery
                    :lazy="true"
                    :size="150"
                    :source="infoList.data.filePathList"
                    title="图片"
                  ></eleGallery>
                </div>
                <span v-else>-</span>
              </template>
            </basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>证照信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="licenseInfoList">
              <template v-slot:basic-licenseNumber>
                <p
                  v-if="$permission('productLicense:details')"
                  class="slip-edit"
                  @click="showLicenseDetail()"
                >
                  {{ infoList.data.licenseNumber || '-' }}
                </p>
                <p v-else>{{ infoList.data.licenseNumber || '-' }}</p>
              </template>
              <template v-slot:basic-brandName>
                <p class="slip-edit" @click="showBrandDetail()">
                  {{ infoList.data.brandName || '-' }}
                </p>
              </template>
            </basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>控制信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="controlInfoList"> </basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>挂网信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="spreadInfoList">
              <template v-slot:basic-networkUnitCoefficient>
                <span>
                  {{ spreadInfoList.data.systemUnitCoefficient || '-' }}
                  {{ spreadInfoList.data.unitName }}
                </span>
                =
                <span>
                  {{ spreadInfoList.data.networkUnitCoefficient || '-' }}
                  {{ spreadInfoList.data.networkUnit }}
                </span>
              </template>
            </basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>分类信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="classifyInfoList"> </basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>医保信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="medicareInfoList"> </basic-information>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <modify-pend-check-product-detail
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :id="modifyInfo.id"
      @returnBack="init"
    />
    <license-details
      v-if="showDetails"
      v-model:visible="showDetails"
      :id="licenseId"
    ></license-details>
  </div>
</template>

<script setup name="pendCheckProductDetails">
import {
  getProductCheck,
  getCoreCodeStatus,
  getCoreProductCheckDifference,
  productCheckRefuse,
  productCheckReject,
  productCheckApproved,
} from '@/api/core'
import { orderOpAffairAll } from '@/api/affair'
import LicenseDetails from './../../product/license/details'
import ModifyPendCheckProductDetail from './modify'
import EleGallery from '@/components/UploadImg/eleGallery'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps(['visible', 'id'])

const title = ref('待审核产品详情')
const showDetails = ref(false)
const licenseId = ref('')
const infoList = reactive({
  diffData: {},
  data: {
    isConsignment: 0,
    withOperateTable: 0,
  },
  fieldList: [
    { label: '通用名称', value: 'commonName', type: 'text', required: true },
    { label: '编码', value: 'code', type: 'text', required: true },
    { label: 'his编码', value: 'hisCode', type: 'text' },
    { label: '别名', value: 'alias', type: 'text' },
    { label: '助记符', value: 'mnemonic', type: 'text' },
    {
      label: '产品类型',
      value: 'productTypeValue',
      type: 'text',
      required: true,
    },
    {
      label: '数量操作模式',
      value: 'qtyOperateModeValue',
      type: 'text',
      required: true,
    },
    { label: '规格', value: 'standard', type: 'text', required: true },
    { label: '型号', value: 'modelNumber', type: 'text' },
    { label: '包装规格', value: 'packingSpecification', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text', required: true },
    { label: '条码类型', value: 'codeTypeValue', type: 'text', required: true },
    {
      label: '原厂主码',
      value: 'mainCode',
      type: 'text',
      required: computed(() => {
        return infoList.data.codeType === 3
      }),
    },
    { label: '原厂码规则', value: 'g1Type', type: 'text' },
    { label: '计量单位', value: 'unitName', type: 'text', required: true },
    { label: '上架状态', value: 'putShelfStatusValue' },
    {
      label: '产品长度(cm)',
      value: 'productLength',
      type: 'text',
    },
    {
      label: '产品宽度(cm)',
      value: 'productWidth',
      type: 'text',
    },
    {
      label: '产品高度(cm)',
      value: 'productHeight',
      type: 'text',
    },

    { label: '创建人', value: 'createUserName' },
    { label: '创建时间', value: 'createTime' },
    { label: '最近更新人', value: 'updateUserName' },
    { label: '最近更新时间', value: 'updateTime' },
    { label: '存储条件', value: 'storageCondition' },
    { label: '备注', value: 'remark', type: 'popover' },
    { label: '审核状态', value: 'checkStatusValue', type: 'text' },
    {
      label: '图片',
      value: 'filePathList',
      specialTreatmentValue: 'name',
      type: 'slot',
      className: 'not-br',
    },
  ],
})
const licenseInfoList = reactive({
  diffData: {},
  data: {
    isConsignment: 0,
    withOperateTable: 0,
  },
  fieldList: [
    { label: '证号', value: 'licenseNumber', type: 'slot', required: true },
    { label: '证照名称', value: 'licenseName', type: 'text' },
    { label: '英文名称', value: 'enName', type: 'text' },
    { label: '证照生效日期', value: 'licenseBeginDate', type: 'text' },
    { label: '证照失效日期', value: 'licenseEndDate', type: 'text' },
    { label: '包装规格', value: 'packedStandard', type: 'text' },

    { label: '生产厂家', value: 'brandName', type: 'slot' },
  ],
})
const controlInfoList = reactive({
  //控制信息
  diffData: {},
  data: {
    isConsignment: 0,
    withOperateTable: 0,
  },
  fieldList: [
    {
      label: '近效期（天）',
      value: 'productNearlyEffective',
      type: 'text',
      required: true,
    },

    {
      label: '需要批号效期',
      value: 'needBatchNumberValue',
      type: 'text',
      required: true,
    },
    {
      label: '需要序列管理',
      value: 'needSequenceValue',
      type: 'text',
      required: true,
    },
    { label: '以领定消', value: 'acquisitionReplaceConsumeValue' },

    { label: '是否议价', value: 'isBargainingValue' },

    { label: '是否收费', value: 'isChargeValue' },
    { label: '是否寄售', value: 'isConsignmentValue' },
    { label: '手术跟台', value: 'withOperateTableValue', type: 'text' },
    { label: '结算方式', value: 'settlementMethodValue', required: true },
    { label: '限制价格', value: 'isLimitPriceValue' },
    { label: '采购限制价格', value: 'purchaseLimitPrice', required: true },
    {
      label: '是否RFID管理',
      value: 'isRfidManageValue',
    },
    { label: '厂家理论测试次数', value: 'expectedUsageTimes', required: true },
    { label: '院内理论测试次数', value: 'hospitalExpectedUsageTimes' },
    { label: '计费次数', value: 'chargeTimes' },
    { label: '重点监控高值医用耗材', value: 'importantHighMaterialValue' },
    { label: '是否集采', value: 'isCollectivePurchaseValue' },
    { label: '集采项目号', value: 'collectivePurchaseBatchValue' },
    { label: '付款类型', value: 'paymentTypeValue' },
  ],
})
const spreadInfoList = reactive({
  diffData: {},
  data: {
    isConsignment: 0,
    withOperateTable: 0,
  },
  fieldList: [
    { label: '是否挂网', value: 'isSunPurchaseValue' },
    {
      label: '挂网类型',
      value: 'networkTypeValue',
      type: 'text',
      required: true,
    },
    {
      label: '挂网产品类型',
      value: 'networkProductTypeValue',
      type: 'text',
      required: true,
    },
    { label: '商品代码', value: 'serialNum', type: 'text', required: true },
    {
      label: '挂网耗材产品id',
      value: 'procureCatalogId',
      type: 'text',
      show: false,
      required: true,
    },
    { label: '挂网单位', value: 'networkUnit', type: 'text', required: true },
    { label: '单位比例', value: 'networkUnitCoefficient', type: 'slot', required: true },
    { label: '挂网单价', value: 'networkPrice', type: 'text' },
  ],
})
const classifyInfoList = reactive({
  diffData: {},
  //分类信息
  data: {
    isConsignment: 0,
    withOperateTable: 0,
  },
  fieldList: [
    {
      label: '财务科目',
      value: 'financialAccountValue',
      type: 'text',
      required: computed(() => {
        let is_need_financial_account =
          proxy.$store.state.permission.systemConfig.is_need_financial_account
        return is_need_financial_account == 1
      }),
    },
    { label: '防疫物资', value: 'epidemicPreventionValue' },
    { label: '临采产品', value: 'temporaryPurchValue' },
    { label: '发票类别', value: 'invoiceCategoryValue' },
    { label: '病案类别', value: 'caseCategoryValue' },
    { label: '质管类型', value: 'dosageFormValue', type: 'text' },
    {
      label: '库存类别',
      value: 'inventoryCategoriesValue',
      type: 'text',
    },
    { label: '产品分类', value: 'productCategoryValue', type: 'text' },
    {
      label: '项目分类',
      value: 'projectClassificationValue',
      type: 'text',
    },
    {
      label: '住院收据费用分类',
      value: 'classificationOfHospitalReceiptsValue',
      type: 'text',
    },
    {
      label: '门诊收据费用分类',
      value: 'outpatientReceiptFeeClassificationValue',
      type: 'text',
    },
    {
      label: '核算项目分类',
      value: 'accountingItemClassificationValue',
      type: 'text',
    },
    {
      label: '病案首页费用分类',
      value: 'medicalRecordsFirstPageCostClassificationValue',
      type: 'text',
    },
    { label: '项目等级', value: 'projectLevelValue', type: 'text' },
    {
      label: '病案首页费用分类',
      value: 'medicalRecordsFirstPageCostClassificationValue',
      type: 'text',
    },
    { label: '项目等级', value: 'projectLevelValue', type: 'text' },
    {
      label: '收费项目会计子分类',
      value: 'chargeItemCategoryValue',
      type: 'text',
    },
    { label: '医嘱子类', value: 'adviceCategoryValue', type: 'text' },
    {
      label: '独立医嘱标记',
      value: 'independentAdviceMarkValue',
      type: 'text',
    },
    { label: '医嘱优先级', value: 'advicePriorityValue', type: 'text' },
    { label: '新病案首页费用分类', value: 'newMedicalRecordsFirstPageCostClassificationValue', type: 'text' },
  ],
})
const medicareInfoList = reactive({
  //医保信息
  diffData: {},
  data: {
    isConsignment: 0,
    withOperateTable: 0,
  },
  fieldList: [
    { label: '国家医保编码', value: 'nationCode', type: 'text' },
    { label: '省医保编码', value: 'provinceCode', type: 'text' },
    {
      label: '国家医保名称',
      value: 'nationHealthInsurance',
      type: 'text',
    },
  ],
})
const affairTableInfo = reactive({
  api: orderOpAffairAll,
  refresh: 1,
  initCurpage: 1,
  data: [],
  query: {
    orderType: 81,
    orderId: props.id,
    sort: 'operate_time desc',
  },
  fieldList: [
    { label: '操作人', value: 'operateUserName' },
    { label: '操作部门', value: 'operateDeptName' },
    { label: '操作时间', value: 'operateTime' },
    { label: '操作类型', value: 'operateTypeValue' },
    { label: '备注', value: 'remark' },
  ],
})
const modifyInfo = reactive({
  visible: false,
  title: '修改产品信息',
  id: '',
})
const fullInfo = reactive({
  btnList: [],
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

watch(
  () => props.visible,
  (newVal) => {
    showDialog.value = newVal
  },
  {
    immediate: true,
  }
)
watch(
  () => props.id,
  (newVal) => {
    init()
    getStatus()
  },
  {
    immediate: true,
    deep: true,
  }
)
watch(
  () => infoList.data.isConsignmentValue,
  (value) => {
    if (value == '是') {
      showFieldListItem(true, 'withOperateTableValue')
    } else {
      showFieldListItem(false, 'withOperateTableValue')
    }
  }
)

function showBrandDetail() {
  emit('toggleBrandDetail', infoList.data.brandId)
}
function showLicenseDetail() {
  sessionStorage.setItem('storeRowId', infoList.data.id)
  licenseId.value = infoList.data.licenseId
  showDetails.value = true
}
function stringFillCharacter(length) {
  return new Array(length + 1).join('x')
}

function showFieldListItem(show, nameValue) {
  let fieldList = infoList.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}

function update() {
  modifyInfo.visible = true
  modifyInfo.type = 'update'
  modifyInfo.id = props.id
  console.log(modifyInfo, 'modifyInfo')
}
// 审核
function approve() {
  let params = {
    orderIds: [infoList.data.id],
  }
  productCheckApproved(params).then((res) => {
    if (res && res.success) {
      init()
      getStatus()
    }
  })
}
function reject() {
  btnFlow(infoList.data, 'reject')
}
function refuse() {
  btnFlow(infoList.data, 'refuse')
}
// 按钮审批原因弹窗
function btnFlow(row, code) {
  let currentBtnFlow = {
    title: '',
    api: null,
  }
  if (code === 'reject') {
    currentBtnFlow.title = '驳回'
    currentBtnFlow.api = productCheckReject
  } else if (code === 'refuse') {
    currentBtnFlow.title = '拒绝'
    currentBtnFlow.api = productCheckRefuse
  }
  proxy
    .$prompt('请输入' + currentBtnFlow.title + '理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: currentBtnFlow.title + '理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderIds: [row.id],
        checkOpt: value,
      }
      currentBtnFlow.api(data).then((resp) => {
        if (resp && resp.success) {
          init()
          getStatus()
        }
      })
    })
}
function getDiff() {
  getCoreProductCheckDifference(infoList.data).then((res) => {
    if (res && res.success) {
      if (res.data?.chargeTimes && res.data?.chargeTimes === -2) {
        res.data.chargeTimes = undefined
      }
      if (res.data && Object.keys(res.data).length) {
        if (
          (infoList.data.codeType == 3 || infoList.data.codeType == 2) &&
          res.data.gsOneRule
        ) {
          if (infoList.data.originType === 'GS1_OTHER') {
            let type = {
              type: 'GS1_OTHER',
              coreProductRuleVOList: res.data.gsOneRule
                ? JSON.parse(res.data.gsOneRule)
                : [],
            }
            const eg = []
            type.coreProductRuleVOList.map((item) => {
              eg.push(
                String(
                  '(' +
                    item.ruleCode +
                    ')' +
                    stringFillCharacter(Number(item.ruleLength))
                )
              )
              return item
            })
            res.data.g1Type = eg.toString().replace(/,/g, '')
          } else {
            // res.data.g1Type = 'GS1规则'
          }
        }
        infoList.diffData = res.data
        licenseInfoList.diffData = res.data
        controlInfoList.diffData = res.data
        spreadInfoList.diffData = res.data
        classifyInfoList.diffData = res.data
        medicareInfoList.diffData = res.data
      }
    }
  })
}
function init() {
  getProductCheck(props.id).then((res) => {
    if (res) {
      if (res.data?.chargeTimes && res.data?.chargeTimes === -2) {
        res.data.chargeTimes = undefined
      }
      infoList.data = res.data
      if (infoList.data.codeType == 3 || infoList.data.codeType == 2) {
        if (infoList.data.originType === 'GS1_OTHER') {
          let type = {
            type: 'GS1_OTHER',
            coreProductRuleVOList: infoList.data.gsOneRule
              ? JSON.parse(infoList.data.gsOneRule)
              : [],
          }
          const eg = []
          type.coreProductRuleVOList.map((item) => {
            eg.push(
              String(
                '(' +
                  item.ruleCode +
                  ')' +
                  stringFillCharacter(Number(item.ruleLength))
              )
            )
            return item
          })
          infoList.data.g1Type = eg.toString().replace(/,/g, '')
        } else {
          infoList.data.g1Type = 'GS1规则'
        }
      } else {
        infoList.data.g1Type = ''
      }
      licenseInfoList.data = infoList.data
      controlInfoList.data = infoList.data
      spreadInfoList.data = infoList.data
      classifyInfoList.data = infoList.data
      medicareInfoList.data = infoList.data
      if (infoList.data.procureCatalogId) {
        spreadInfoList.fieldList.forEach((item) => {
          if (item.value === 'procureCatalogId') {
            item.show = true
          }
        })
      }
      getDiff()
      if (infoList.data.needLicense == 1) {
        requiredFieldListItem(true, 'licenseNumber', licenseInfoList.fieldList)
      } else {
        requiredFieldListItem(false, 'licenseNumber', licenseInfoList.fieldList)
      }
      if (infoList.data.isSunPurchase == 1) {
        requiredFieldListItem(
          true,
          'networkTypeValue',
          spreadInfoList.fieldList
        )
        requiredFieldListItem(
          true,
          'networkProductTypeValue',
          spreadInfoList.fieldList
        )
        requiredFieldListItem(true, 'serialNum', spreadInfoList.fieldList)
        requiredFieldListItem(
          true,
          'procureCatalogId',
          spreadInfoList.fieldList
        )
        requiredFieldListItem(true, 'networkUnit', spreadInfoList.fieldList)
        requiredFieldListItem(true, 'networkUnitCoefficient', spreadInfoList.fieldList)
        if (infoList.data.networkProductType == 1) {
          requiredFieldListItem(
            false,
            'procureCatalogId',
            spreadInfoList.fieldList
          )
        } else if (infoList.data.networkProductType == 2) {
          requiredFieldListItem(
            true,
            'procureCatalogId',
            spreadInfoList.fieldList
          )
        }
      } else {
        requiredFieldListItem(
          false,
          'networkTypeValue',
          spreadInfoList.fieldList
        )
        requiredFieldListItem(
          false,
          'networkProductTypeValue',
          spreadInfoList.fieldList
        )
        requiredFieldListItem(false, 'serialNum', spreadInfoList.fieldList)
        requiredFieldListItem(
          false,
          'procureCatalogId',
          spreadInfoList.fieldList
        )
        requiredFieldListItem(false, 'networkUnit', spreadInfoList.fieldList)
        requiredFieldListItem(false, 'networkUnitCoefficient', spreadInfoList.fieldList)
      }
    }
  })
}
function getStatus() {
  getCoreCodeStatus({ codeType: '2' }).then((res) => {
    requiredFieldListItem(!res.data, 'code', infoList.fieldList)
  })
}
function requiredFieldListItem(required, nameValue, fieldList) {
  // let fieldList = infoList.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.required = required
    }
  })
}
function getFlowFormInfo() {
  return infoList.data
}
defineExpose({
  getFlowFormInfo
})
</script>

<style scoped></style>
